import axios, {
  AxiosError,
  type AxiosRequestConfig,
  type AxiosResponse,
  type InternalAxiosRequestConfig,
} from "axios";

const BASE_URL = "http://192.168.8.14:3000";

//创建axios实例
const instance = axios.create({
  baseURL: BASE_URL,
  timeout: 3000,
  headers: {
    "Content-Type": "application/json",
  },
});

//创建请求拦截器
instance.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    console.log("1.请求参数:" + JSON.stringify(config));
    return config;
  },
  (error: AxiosError) => {
    console.log("3.异常信息:" + JSON.stringify(error));
    return Promise.reject(error);
  }
);

//创建响应拦截器
instance.interceptors.response.use(
  (response: AxiosResponse) => {
    //响应成功
    if (response.data.code === 200) {
      // console.log("响应结果:" + JSON.stringify(response.data));
      return response.data;
    }
    // console.log("完整响应:" + JSON.stringify(response.data.data));
  },
  (error: AxiosError) => {
    if (error.response?.status === 401) {
      uni.showToast({
        icon: "error",
        title: "登录超时!",
      });
      // console.log(JSON.stringify(error.response.data, null, 2));
      return Promise.reject(error.response.data);
    }

    //打印后台错误信息
    console.error(
      "4.异常信息:" + JSON.stringify(error.response?.data, null, 2)
    );
    return Promise.reject(error.response?.data);
  }
);

//导出创建自定义请求
export class http {
  static get<T>(url: string, params?: object) {
    return instance.get<null, T>(url, { params });
  }

  static post<T>(url: string, data?: object) {
    return instance.post<null, T>(url, data);
  }

  static put<T>(url: string, data?: object) {
    return instance.put<null, T>(url, data);
  }

  static delete<T>(url: string, data?: object) {
    return instance.delete<null, T>(url, data);
  }
}
